package com.putong35.easyui.search;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.putong35.common.baseactfrag.activity.BaseActivity;
import com.putong35.easyui.R;

public class SearchActivity extends BaseActivity implements OnSearchKeyChangedListener {

    public static void start(Context fromContext) {
        Intent intent = new Intent(fromContext, SearchActivity.class);
        fromContext.startActivity(intent);

    }

    private String lastSearchKey;
    HistoryFragment historyFragment;
    ResultFragment resulFragment;
    PromptFragment promptFragment;

    Button btnClose;
    EditText etContent;
    ImageView ivClear;
    FrameLayout lytHistory;
    FrameLayout lytResult;
    FrameLayout lytPrompt;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        hideToolbar();
        initViews();

        historyFragment = new HistoryFragment();
        resulFragment = new ResultFragment();
        promptFragment = new PromptFragment();

        getSupportFragmentManager().beginTransaction().add(R.id.lytHistory, historyFragment).commit();
        getSupportFragmentManager().beginTransaction().add(R.id.lytResult, resulFragment).commit();
        getSupportFragmentManager().beginTransaction().add(R.id.lytPrompt, promptFragment).commit();

        getSupportFragmentManager().beginTransaction().hide(resulFragment).commit();
        getSupportFragmentManager().beginTransaction().hide(promptFragment).commit();
    }

    @Override
    public View createDataView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.search_activity_search, null);
    }

    private void initViews() {
        lytHistory = (FrameLayout) findViewById(R.id.lytHistory);
        lytPrompt = (FrameLayout) findViewById(R.id.lytPrompt);
        lytResult = (FrameLayout) findViewById(R.id.lytResult);

        btnClose = (Button) findViewById(R.id.btnClose);
        etContent = (EditText) findViewById(R.id.etContent);
        ivClear = (ImageView) findViewById(R.id.ivClear);
        ivClear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                etContent.setText("");
            }
        });
        btnClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        // 监听EditText的输入变化
        etContent.addTextChangedListener(editTextChangedListener);

        etContent.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    // 先隐藏键盘
                    if (getCurrentFocus() != null && getCurrentFocus().getWindowToken() != null) {
                        ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(
                                getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                    }
                    String searchText = etContent.getText().toString().trim();
                    if (!TextUtils.equals(lastSearchKey, searchText)) {
                        onSearchKeyChanged(searchText);
                    }
                }
                return true;
            }


        });

    }

    TextWatcher editTextChangedListener =  new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            promptFragment.onTextChanged(s);

        }

        @Override
        public void afterTextChanged(Editable s) {
        }
    };


    /**
     * 不仅仅输入框的输入可以触发此事件，historyFragment、promptFragment都可以触发这个事件
     *
     * 此事件触发之后，只显示ResultFragment，其他Fragment必须隐藏。
     * @param searchText
     */
    public void onSearchKeyChanged(String searchText) {
        lastSearchKey = searchText;

        // 同步更新EdtiText里的内容，为了避免重复触发TextChanged，promptFragment重复打开，先把监听器删除了
        if (!TextUtils.equals(etContent.getText().toString(), searchText)) {
            etContent.removeTextChangedListener(editTextChangedListener);
            etContent.setText(searchText);
            etContent.addTextChangedListener(editTextChangedListener);
        }

        // 避免重复触发TextChanged，promptFragment重复打开
        promptFragment.onSearchKeyChanged(searchText);

        if (historyFragment.isVisible()) {
            getSupportFragmentManager().beginTransaction().hide(historyFragment).commitAllowingStateLoss();
        }

        // 显示ResultFragment，并传递事件

        if (!resulFragment.isVisible()) {
            getSupportFragmentManager().beginTransaction().show(resulFragment).commitAllowingStateLoss();
        }
        resulFragment.onSearchKeyChanged(searchText);

    }
}
